<template>
  <div class="transfer-organization" v-if="[4, 5].includes(data.user.userType)">
    <!-- 转接申请区域 -->
    <el-card class="transfer-card" v-if="!data.applicationSubmitted">
      <template #header>
        <div class="card-header">
          <span>团组织关系转接申请</span>
        </div>
      </template>

      <el-form :model="form" label-width="120px">
        <el-form-item label="学生姓名">
          <el-input v-model="data.user.realName" placeholder="请输入学生姓名" disabled/>
        </el-form-item>

        <el-form-item label="转出组织" required>
          <el-input v-model="data.branchName" disabled=""/>
        </el-form-item>

        <el-form-item label="转入组织" required>
          <el-select
              v-model="data.inBranch"
              filterable
              placeholder="请选择所属支部"
              clearable
          >
            <el-option
                v-for="item in data.branchOptions"
                :key="item.id"
                :label="item.branchName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="转接理由" required>
          <el-input v-model="form.reason" type="textarea" rows="3" placeholder="请输入转接理由"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitApplication">提交转接申请</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 审批进度 -->
    <el-card class="approval-card" v-if="data.applicationSubmitted">
      <template #header>
        <div class="card-header">
          <span>审批进度</span>
        </div>
      </template>

      <el-steps :active="data.status" finish-status="success" process-status="wait" space="200px">
        <el-step title="转出团支部审批" :description="getStepDescription(0)"/>
        <el-step title="转出上级组织审批" :description="getStepDescription(1)"/>
        <el-step title="转入团支部审批" :description="getStepDescription(2)"/>
        <el-step title="转入上级组织审批" :description="getStepDescription(3)"/>
        <el-step title="完成" :description="getStepDescription(4)"/>
      </el-steps>

    </el-card>
  </div>

  <div v-else>
    <!-- 显示所有转接申请 -->
    <el-card class="applications-list">
      <template #header>
        <div class="card-header">
          <span>转接申请列表</span>
        </div>
      </template>
      <el-table :data="data.applications" style="width: 100%">
        <el-table-column label="学生姓名" prop="studentName"></el-table-column>
        <el-table-column label="转出组织" prop="transferOutOrganizationName"></el-table-column>
        <el-table-column label="转入组织" prop="transferInOrganizationName"></el-table-column>
        <el-table-column label="转接理由" prop="reason"></el-table-column>
        <el-table-column label="申请状态" prop="status">
          <template #default="{ row }">
            <span>{{ getStatusLabel(row.status) }}</span>
          </template>
        </el-table-column>
        <!-- 审批按钮列 -->
        <el-table-column label="操作" style="width: 200px">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="success" @click="approveStep(row)" v-if="row.status < 5">同意</el-button>
              <el-button type="danger" @click="del(row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {getUserInfo} from "@/utils/auth";
import request from '@/utils/request';

const data = reactive({
  user: getUserInfo() || {},
  branchOptions: [],
  inBranch: '',
  outBranch: '',
  applications: [], // 审批数据
  applicationSubmitted: false, // 审批流程
  status: 0, // 审批进度
  branchName: null,
});

const form = reactive({
  studentName: data.user.realName,
  studentId: data.user.id,
  transferOutOrganization: '',
  transferInOrganization: '',
  reason: '',
});

const approvalStep = ref(data.status);

// 通用请求函数
const fetchData = async (url, params = {}) => {
  try {
    const res = await request.get(url, {params});
    if (res.code === '200') {
      return res.data;
    } else {
      ElMessage.error(res.msg || '请求失败');
      throw new Error(res.msg || '请求失败');
    }
  } catch (error) {
    ElMessage.error(error.message);
    throw error;
  }
};

// 加载支部选项
const loadBranchOptions = async () => {
  data.branchOptions = await fetchData('/organizationBranch/selectAll');
};

// 获取申请状态
const loadApplicationsStatus = async () => {
  const res = await fetchData('/transferProcess/getByUserId/' + data.user.id);
  if (res.length) {
    data.applicationSubmitted = true;
    data.status = res[0].status;
  }
  request.get('organizationMember/selectById/' + data.user.id).then(res => {
    if (res.code === '200') {
      data.branchName = res.data.branchName
      data.outBranch = res.data.branchId
    } else {
      ElMessage.error(res.msg || '团组织查询失败');
    }
  })
};

// 获取转接申请列表
const loadApplications = async () => {
  data.applications = await fetchData('/transferProcess/selectAll', {
    userId: data.user.id,
  });
};

// 获取分支领导人和上级领导
const getBranchLeaders = async (branchId) => {
  const branch = await fetchData(`/organizationBranch/selectById/${branchId}`);
  const parentBranch = await fetchData(`/organizationBranch/selectById/${branch.parentId}`);
  return {
    branchApprover: branch.leaderId,
    higherApprover: parentBranch.leaderId
  };
};

// 提交转接申请
const submitApplication = async () => {
  form.transferOutOrganization = data.outBranch;
  form.transferInOrganization = data.inBranch;
  console.log(form)
  try {
    const [outBranchLeaders, inBranchLeaders] = await Promise.all([
      getBranchLeaders(data.outBranch),
      getBranchLeaders(data.inBranch)
    ]);

    form.transferOutBranchApprover = outBranchLeaders.branchApprover;
    form.transferOutHigherApprover = outBranchLeaders.higherApprover;
    form.transferInBranchApprover = inBranchLeaders.branchApprover;
    form.transferInHigherApprover = inBranchLeaders.higherApprover;
  } catch (error) {
    ElMessage.error('获取领导信息失败');
    return;
  }

  // 校验必填项
  if (!form.studentName || !form.transferOutOrganization || !form.transferInOrganization || !form.reason) {
    ElMessage.warning('请填写所有必填项');
    return;
  }

  try {
    const res = await request.post('/transferProcess/add', form);
    if (res.code === '200') {
      data.applicationSubmitted = true;
      ElMessage.success('转接申请已提交');
    } else {
      ElMessage.error(res.msg || '转接申请提交失败');
    }
  } catch (error) {
    console.error('转接申请提交失败:', error);
    ElMessage.error('转接申请提交失败');
  }
};

// 删除单条数据
const del = (id) => {
  ElMessageBox.confirm('确定要删除这个申请吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await request.delete('/transferProcess/delete/' + id);
    ElMessage.success('删除成功');
    loadApplications();
  }).catch(() => {
  });
};

// 审批步骤
const approveStep = async (application) => {
  try {
    const res = await request.put('/transferProcess/update', {
      id: application.id,
      status: application.status + 1,
    });
    if(application.status === 3) {
      await request.put('/transferProcess/update', {
        id: application.id,
        status: application.status + 2,
      });
      console.log(application)
      await request.put('/organizationMember/update', {
        userId: application.studentId,
        branchId: application.transferInOrganization,
      });
    }
    if (res.code === '200') {
      ElMessage.success('操作成功');
      await loadApplications();  // 重新加载申请列表
    } else {
      ElMessage.error(res.msg || '审批失败');
    }
  } catch (error) {
    console.error('审批失败:', error);
    ElMessage.error('审批失败');
  }
};

// 审批流程图
const getStepDescription = (step) => {
  const stepDescriptions = [
    '审批', '审批', '审批', '审批', '审批', '转接完成'
  ];
  return step >= 0 && step <= 5 ? stepDescriptions[step] : '未知状态';
};

// 获取当前的审批状态
const getStatusLabel = (status) => {
  const statusLabels = [
    '待审批', '转出团支部审批', '转出上级组织审批', '转入团支部审批', '转入上级组织审批', '转接完成'
  ];
  return statusLabels[status] || '未知状态';
};

// 组件挂载后加载支部选项和申请列表
onMounted(() => {
  if ([4, 5].includes(data.user.userType)) {
    loadBranchOptions();
    loadApplicationsStatus();
  } else {
    loadApplications();
  }
});
</script>

<style scoped>
.transfer-organization {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.transfer-card, .approval-card {
  margin-bottom: 20px;
}

.applications-list {
  margin-top: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
</style>
